package JDBC;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 87111
 * Date: 2025-10-24
 * Time: 15:13
 */
public class demo1 {
    public static void main(String[] args) throws SQLException {
        Scanner sc = new Scanner(System.in);
        //1. 创建数据源
        //设置数据源的数据串，用户名，密码
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java1024?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        //2.建立数据库连接
        Connection connection = dataSource.getConnection();

        //3. java代码编写SQL语句
//        String sql1 = "insert into student values(1,'张三');";
//        Statement statement = connection.createStatement();//创建sql连接对象（相当于命令窗口）

        System.out.println("请输入id:");
        int id = sc.nextInt();
        System.out.println("请输入名字:");
        String name = sc.next();

        String sql2 = "insert into student values(?,?);";
        PreparedStatement statement = connection.prepareStatement(sql2);
        statement.setInt(1,id);
        statement.setString(2,name);


        //4. 将SQL语句发送给MySQL服务器执行
//        int a = statement.executeUpdate(sql1);//执行sql语句，并返回影响的行数（相当于输入命令）

        int b = statement.executeUpdate();//增删改

//        Resu c = statement.executeQuery(); 查

        //5. 释放资源，释放资源顺序与创建资源顺序相反
        statement.close();
        connection.close();
    }
}
